package ccnu.agile.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

/**
 * @AUTHOR Jream.Y
 * @CREATE 2021-09-02
 */
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationCtontext = null;

    private static String applicationModuleName;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LogUtils.info(this, "inject applicationContext:{}", applicationContext.getApplicationName());
        if (applicationContext != null) {
            LogUtils.error("ApplicationContext is overide, old ApplicationContext:" + applicationContext.getApplicationName());
        }

        SpringUtils.applicationCtontext = applicationContext;
    }

    /**
     * getApplicationContext:获取当前运行的Spring容器
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationCtontext;
    }

    /**
     * getBean:根据类型从容器中获取bean对象
     */
    public static <T> T getBean(String name, Class<T> requiredType) {
        return getApplicationContext().getBean(name, requiredType);
    }

    /**
     * getBean:根据类型从容器中获取bean对象
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * getBean:根据类型从容器中获取bean对象
     */
    public static <T> T getBean(Class<T> requiredType) {
        return getApplicationContext().getBean(requiredType);
    }

    public static ApplicationContext getApplicationCtontext() {
        return applicationCtontext;
    }

    public static void setApplicationCtontext(ApplicationContext applicationCtontext) {
        SpringUtils.applicationCtontext = applicationCtontext;
    }

    public static String getApplicationModuleName() {
        String moduleName = StringUtils.isEmpty(applicationModuleName) && applicationCtontext != null ? applicationCtontext.getApplicationName() : applicationModuleName;
        if (!StringUtils.isEmpty(moduleName) && moduleName.startsWith("/")) {
            moduleName = moduleName.replaceFirst("/", "");
        }
        return moduleName;
    }

    public static void setApplicationModuleName(String applicationModuleName) {
        SpringUtils.applicationModuleName = applicationModuleName;
    }

}
